#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/3/20
# @USER    : Shengji He
# @File    : CountSymmetricIntegers.py
# @Software: PyCharm
# @Version  : Python-
# @TASK:

"""
- Math
- Enumeration
"""

symmetric_count = [0] * 10002


def count_symmetric_integers() -> None:
    count_symmetric = 0
    for current_num in range(10002):
        x = str(current_num)
        n = len(x)
        if n % 2 == 1:  # Ignore odd-length numbers
            symmetric_count[current_num] = count_symmetric
            continue
        if sum(map(int, x[:n // 2])) == sum(map(int, x[n // 2:])):
            count_symmetric += 1
        symmetric_count[current_num] = count_symmetric


count_symmetric_integers()


class Solution:
    """
    [2843. Count Symmetric Integers](https://leetcode.com/problems/count-symmetric-integers/description/)

    You are given two positive integers low and high.

    An integer x consisting of 2 * n digits is symmetric if the sum of the first n digits of x is equal to the sum of the last n digits of x. Numbers with an odd number of digits are never symmetric.

    Return the number of symmetric integers in the range [low, high].

    Example 1:
        Input: low = 1, high = 100
        Output: 9
        Explanation: There are 9 symmetric integers between 1 and 100: 11, 22, 33, 44, 55, 66, 77, 88, and 99.

    Example 2:
        Input: low = 1200, high = 1230
        Output: 4
        Explanation: There are 4 symmetric integers between 1200 and 1230: 1203, 1212, 1221, and 1230.

    Constraints:
        - 1 <= low <= high <= 104
    """

    def countSymmetricIntegers(self, low: int, high: int) -> int:
        count = 0
        for number in range(low, high + 1):
            s = str(number)
            length = len(s)
            if length % 2 != 0:
                continue
            n = length // 2
            prefix = sum(int(i) for i in s[:n])
            postfix = sum(int(i) for i in s[n:])
            if prefix == postfix:
                count += 1
        return count

    def countSymmetricIntegers_v2(self, low: int, high: int) -> int:
        """pre calculate"""
        return symmetric_count[high] - symmetric_count[low - 1]

    def countSymmetricIntegers_v3(self, low: int, high: int) -> int:
        c = 0

        for i in range(low, high + 1):
            if 10 <= i < 100:
                if i // 10 == i % 10:
                    c += 1
            if 1000 <= i < 10000:
                n = i // 100
                m = i % 100
                if (n // 10 + n % 10) == (m // 10 + m % 10):
                    c += 1
        return c


if __name__ == '__main__':
    low = 1200
    high = 1230
    S = Solution()
    print(S.countSymmetricIntegers(low, high))
    print('done')
